document.addEventListener('DOMContentLoaded', function() {
    // 1. 初始化Bootstrap工具提示
    initTooltips();

    // 2. 考试科目展开/收起交互
    initSubjectToggle();

    // 3. 成绩备注展开/收起交互
    initNoteToggle();

    // 4. 目标成绩卡片交互
    initTargetScoreCards();

    // 5. 成绩分析卡片交互
    initAnalysisCardInteractions();

    // 6. 进度条动画
    initProgressAnimations();

    // 7. 相对时间计算兜底
    initRelativeTimeFallback();

    // 8. 初始化删除确认
    initDeleteConfirmations();

    // 9. 初始化成绩操作按钮的工具提示
    initScoreActionTooltips();

    // 10. 初始化分数范围计算
    initScoreRangeCalculations();
});

/**
 * 1. 初始化Bootstrap工具提示
 */
function initTooltips() {
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    if (tooltipTriggerList.length > 0) {
        const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                trigger: 'hover',
                delay: { show: 300, hide: 100 },
                placement: 'top'
            });
        });

        // 窗口调整大小时更新工具提示位置
        window.addEventListener('resize', () => {
            tooltipList.forEach(tooltip => tooltip.update());
        });
    }
}

/**
 * 2. 考试科目展开/收起交互
 */
function initSubjectToggle() {
    const subjectToggle = document.querySelector('.subject-toggle');
    const subjectContent = document.querySelector('.subject-content');

    if (subjectToggle && subjectContent) {
        let isExpanded = true;

        subjectToggle.addEventListener('click', function() {
            isExpanded = !isExpanded;

            if (isExpanded) {
                // 展开内容
                subjectContent.style.display = 'block';
                subjectContent.style.opacity = '0';
                subjectContent.style.transition = 'opacity 0.3s ease';

                setTimeout(() => {
                    subjectContent.style.opacity = '1';
                }, 10);

                this.innerHTML = '<i class="bi bi-chevron-up me-1"></i>收起';
            } else {
                // 收起内容
                subjectContent.style.opacity = '0';
                subjectContent.style.transition = 'opacity 0.3s ease';

                setTimeout(() => {
                    subjectContent.style.display = 'none';
                }, 300);

                this.innerHTML = '<i class="bi bi-chevron-down me-1"></i>展开';
            }
        });
    }
}

/**
 * 3. 成绩备注展开/收起交互
 */
function initNoteToggle() {
    const noteToggles = document.querySelectorAll('.note-toggle');

    noteToggles.forEach(toggle => {
        const noteContent = toggle.nextElementSibling;
        let isExpanded = false;

        toggle.addEventListener('click', function() {
            isExpanded = !isExpanded;

            if (isExpanded) {
                // 展开备注
                noteContent.classList.remove('d-none');
                const contentHeight = noteContent.scrollHeight;

                noteContent.style.height = '0';
                noteContent.style.opacity = '0';
                noteContent.style.overflow = 'hidden';
                noteContent.style.transition = 'height 0.3s ease, opacity 0.3s ease';

                setTimeout(() => {
                    noteContent.style.height = `${contentHeight}px`;
                    noteContent.style.opacity = '1';
                }, 10);

                this.innerHTML = '<i class="bi bi-chevron-up me-1"></i>收起备注';
            } else {
                // 收起备注
                noteContent.style.height = '0';
                noteContent.style.opacity = '0';

                setTimeout(() => {
                    noteContent.classList.add('d-none');
                    noteContent.style.height = '';
                }, 300);

                this.innerHTML = '<i class="bi bi-chevron-down me-1"></i>查看备注';
            }
        });
    });
}

/**
 * 4. 目标成绩卡片交互
 */
function initTargetScoreCards() {
    const targetScoreCards = document.querySelectorAll('.target-score-card');

    targetScoreCards.forEach(card => {
        // 悬停效果
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-6px)';
            this.style.boxShadow = '0 16px 40px rgba(0, 0, 0, 0.12)';
            this.style.borderColor = 'var(--primary-300)';
        });

        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(-4px)';
            this.style.boxShadow = '0 12px 40px rgba(0, 0, 0, 0.1)';
            this.style.borderColor = '#e2e8f0';
        });

        // 点击卡片跳转到编辑页面（排除操作按钮区域）
        card.addEventListener('click', function(e) {
            // 如果点击的是操作按钮或链接，不跳转
            if (e.target.closest('.target-score-actions') ||
                e.target.tagName === 'A' ||
                e.target.tagName === 'BUTTON' ||
                e.target.closest('a') ||
                e.target.closest('button')) {
                return;
            }

            const editLink = this.querySelector('a[href*="target_score_update"]');
            if (editLink) {
                window.location.href = editLink.href;
            }
        });

        // 操作按钮悬停效果
        const actionButtons = card.querySelectorAll('.btn-action');
        actionButtons.forEach(btn => {
            btn.addEventListener('mouseenter', function(e) {
                e.stopPropagation();
                this.style.transform = 'translateY(-2px) scale(1.05)';
            });

            btn.addEventListener('mouseleave', function(e) {
                e.stopPropagation();
                this.style.transform = 'translateY(0) scale(1)';
            });
        });

        // 分数对比区域的悬停效果
        const scoreComparison = card.querySelector('.score-comparison');
        if (scoreComparison) {
            scoreComparison.addEventListener('mouseenter', function() {
                this.style.background = 'linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%)';
                this.style.borderColor = 'var(--primary-200)';
                this.style.transform = 'scale(1.02)';
            });

            scoreComparison.addEventListener('mouseleave', function() {
                this.style.background = 'linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%)';
                this.style.borderColor = '#e2e8f0';
                this.style.transform = 'scale(1)';
            });
        }
    });

    // 初始化卡片入场动画
    initTargetCardsAnimation();
}

/**
 * 目标成绩卡片入场动画
 */
function initTargetCardsAnimation() {
    const targetCards = document.querySelectorAll('.target-score-card');

    targetCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px) scale(0.95)';

        setTimeout(() => {
            card.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0) scale(1)';
        }, 100 + (index * 150));
    });
}

/**
 * 5. 成绩分析卡片交互
 */
function initAnalysisCardInteractions() {
    // 高亮卡片悬停效果
    const highlightCards = document.querySelectorAll('.highlight-card');
    highlightCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-4px)';
            this.style.boxShadow = '0 12px 30px rgba(0, 0, 0, 0.15)';
        });

        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(-2px)';
            this.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.1)';
        });
    });

    // 风险评估项点击效果
    const riskItems = document.querySelectorAll('.risk-item');
    riskItems.forEach(item => {
        item.addEventListener('click', function() {
            this.style.transform = 'scale(0.98)';
            setTimeout(() => {
                this.style.transform = '';
            }, 150);

            // 这里可以添加风险评估详情查看逻辑
            const riskCategory = this.querySelector('.risk-category').textContent;
            const riskCount = this.querySelector('.risk-count').textContent;
            console.log('查看风险评估详情:', riskCategory, riskCount);
        });
    });

    // 行动建议项点击效果
    const suggestionItems = document.querySelectorAll('.suggestion-item');
    suggestionItems.forEach(item => {
        item.addEventListener('click', function() {
            this.style.transform = 'translateX(8px)';
            setTimeout(() => {
                this.style.transform = 'translateX(4px)';
            }, 150);

            // 这里可以添加行动建议详情逻辑
            const suggestionText = this.querySelector('span').textContent;
            console.log('查看行动建议:', suggestionText);
        });
    });

    // 进度统计悬停效果
    const progressStats = document.querySelectorAll('.progress-stat');
    progressStats.forEach(stat => {
        stat.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
            this.style.transition = 'transform 0.3s ease';
        });

        stat.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    });
}

/**
 * 6. 进度条动画
 */
function initProgressAnimations() {
    // 目标成绩进度条动画
    const progressBarFills = document.querySelectorAll('.progress-bar-fill');
    progressBarFills.forEach(bar => {
        const originalWidth = bar.style.width;
        if (originalWidth && originalWidth !== '0%') {
            bar.style.width = '0';
            setTimeout(() => {
                bar.style.width = originalWidth;
                bar.style.transition = 'width 1s ease-in-out 0.5s';
            }, 500);
        }
    });

    // 分数范围条动画
    const rangeBars = document.querySelectorAll('.range-safety, .range-realistic, .range-ideal');
    rangeBars.forEach(bar => {
        const originalWidth = bar.style.width;
        if (originalWidth && originalWidth !== '0%') {
            bar.style.width = '0';
            setTimeout(() => {
                bar.style.width = originalWidth;
                bar.style.transition = 'width 0.8s ease-in-out 0.3s';
            }, 300);
        }
    });

    // 当前分数指示器动画
    const rangeCurrents = document.querySelectorAll('.range-current');
    rangeCurrents.forEach(indicator => {
        const originalLeft = indicator.style.left;
        if (originalLeft) {
            indicator.style.left = '0%';
            setTimeout(() => {
                indicator.style.left = originalLeft;
                indicator.style.transition = 'left 1s ease-in-out 0.7s';
            }, 700);
        }
    });

    // 圆形进度条动画
    const statCircles = document.querySelectorAll('.stat-circle');
    statCircles.forEach(circle => {
        const progress = circle.getAttribute('data-progress') || 0;
        const circlePath = circle.querySelector('circle:last-child');

        if (circlePath) {
            const circumference = 2 * Math.PI * 27; // r=27
            const offset = circumference - (progress / 100) * circumference;

            circlePath.style.strokeDasharray = `${circumference}`;
            circlePath.style.strokeDashoffset = `${circumference}`;

            setTimeout(() => {
                circlePath.style.transition = 'stroke-dashoffset 1.5s ease-in-out 1s';
                circlePath.style.strokeDashoffset = `${offset}`;
            }, 1000);
        }
    });

    // 分析卡片入场动画
    const analysisCards = document.querySelectorAll('.analysis-highlights, .risk-assessment, .progress-overview, .action-suggestions');
    analysisCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';

        setTimeout(() => {
            card.style.transition = 'all 0.6s ease';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 300 + (index * 200));
    });
}

/**
 * 7. 相对时间计算兜底
 */
function initRelativeTimeFallback() {
    // 如果moment.js可用，使用它来计算相对时间
    if (typeof moment !== 'undefined') {
        const timeElements = document.querySelectorAll('.system-value .small');

        timeElements.forEach(el => {
            const timeText = el.textContent.trim();

            // 只处理包含具体时间格式的文本
            if (timeText && !timeText.includes('刚刚') && !timeText.includes('天前') &&
                !timeText.includes('月前') && !timeText.includes('年前') && !timeText.includes('今天')) {

                const timeMatch = timeText.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/);
                if (timeMatch) {
                    try {
                        const relativeTime = moment(timeMatch[0]).fromNow();
                        el.textContent = relativeTime;
                    } catch (error) {
                        console.log('时间格式解析失败:', error);
                    }
                }
            }
        });
    } else {
        // 简单的相对时间计算兜底
        const timeElements = document.querySelectorAll('.system-value .small');
        const now = new Date();

        timeElements.forEach(el => {
            const timeText = el.textContent.trim();
            const timeMatch = timeText.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/);

            if (timeMatch) {
                try {
                    const timeDate = new Date(timeMatch[0].replace(' ', 'T'));
                    const diffMs = now - timeDate;
                    const diffMins = Math.floor(diffMs / (1000 * 60));
                    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
                    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

                    let relativeTime = '';
                    if (diffMins < 1) {
                        relativeTime = '刚刚';
                    } else if (diffMins < 60) {
                        relativeTime = `${diffMins}分钟前`;
                    } else if (diffHours < 24) {
                        relativeTime = `${diffHours}小时前`;
                    } else if (diffDays < 30) {
                        relativeTime = `${diffDays}天前`;
                    } else if (diffDays < 365) {
                        relativeTime = `${Math.floor(diffDays / 30)}月前`;
                    } else {
                        relativeTime = `${Math.floor(diffDays / 365)}年前`;
                    }

                    el.textContent = relativeTime;
                } catch (error) {
                    console.log('时间计算失败:', error);
                }
            }
        });
    }
}

/**
 * 8. 初始化删除确认
 */
function initDeleteConfirmations() {
    const deleteForms = document.querySelectorAll('form[action*="past-score"], form[action*="target_score"]');

    deleteForms.forEach(form => {
        const submitBtn = form.querySelector('button[type="submit"]');

        if (submitBtn) {
            submitBtn.addEventListener('click', function(e) {
                let confirmMessage = '';

                if (form.action.includes('past-score')) {
                    const examYear = this.closest('.score-item').querySelector('.score-year').textContent;
                    confirmMessage = `确定要删除 ${examYear} 成绩吗？此操作不可撤销。`;
                } else if (form.action.includes('target_score')) {
                    const subjectName = this.closest('.target-score-card').querySelector('.subject-name').textContent.trim();
                    confirmMessage = `确定要删除 ${subjectName} 的目标成绩吗？此操作不可撤销。`;
                }

                const confirmed = confirm(confirmMessage);

                if (!confirmed) {
                    e.preventDefault();
                }
            });
        }
    });
}

/**
 * 9. 初始化成绩操作按钮的工具提示
 */
function initScoreActionTooltips() {
    const editButtons = document.querySelectorAll('.btn-edit');
    const deleteButtons = document.querySelectorAll('.btn-delete');

    // 为编辑按钮添加工具提示
    [...editButtons].forEach(button => {
        new bootstrap.Tooltip(button, {
            trigger: 'hover',
            delay: { show: 300, hide: 100 },
            placement: 'top',
            title: button.getAttribute('data-bs-title') || '编辑'
        });
    });

    // 为删除按钮添加工具提示
    [...deleteButtons].forEach(button => {
        new bootstrap.Tooltip(button, {
            trigger: 'hover',
            delay: { show: 300, hide: 100 },
            placement: 'top',
            title: button.getAttribute('data-bs-title') || '删除'
        });
    });
}

/**
 * 10. 初始化分数范围计算
 */
function initScoreRangeCalculations() {
    const targetCards = document.querySelectorAll('.target-score-card');

    targetCards.forEach(card => {
        const maxScore = getMaxScoreForSubject(card.dataset.subject);
        const currentScore = parseFloat(card.querySelector('.current-score .score-value').textContent) || 0;
        const safetyScore = parseFloat(card.querySelector('.range-labels span:first-child').textContent.replace('保底 ', '')) || 0;
        const idealScore = parseFloat(card.querySelector('.range-labels span:last-child').textContent.replace('理想 ', '')) || 0;
        const realisticScore = parseFloat(card.querySelector('.target-score .score-value').textContent) || 0;

        // 计算百分比
        const safetyPercent = (safetyScore / maxScore) * 100;
        const realisticPercent = (realisticScore / maxScore) * 100;
        const idealPercent = (idealScore / maxScore) * 100;
        const currentPercent = (currentScore / maxScore) * 100;

        // 更新范围条
        const rangeSafety = card.querySelector('.range-safety');
        const rangeRealistic = card.querySelector('.range-realistic');
        const rangeIdeal = card.querySelector('.range-ideal');
        const rangeCurrent = card.querySelector('.range-current');

        if (rangeSafety) rangeSafety.style.width = `${Math.min(safetyPercent, 100)}%`;
        if (rangeRealistic) rangeRealistic.style.width = `${Math.min(realisticPercent, 100)}%`;
        if (rangeIdeal) rangeIdeal.style.width = `${Math.min(idealPercent, 100)}%`;
        if (rangeCurrent) rangeCurrent.style.left = `${Math.min(currentPercent, 100)}%`;

        // 添加分数变化动画
        animateScoreChange(card, currentScore, realisticScore);
    });
}

/**
 * 根据科目获取最大分数
 */
function getMaxScoreForSubject(subject) {
    const maxScores = {
        'politics': 100,
        'english': 100,
        'math': 150,
        'professional_1': 150,
        'professional_2': 150
    };
    return maxScores[subject] || 150;
}

/**
 * 分数变化动画
 */
function animateScoreChange(card, currentScore, targetScore) {
    const currentValue = card.querySelector('.current-score .score-value');
    const targetValue = card.querySelector('.target-score .score-value');

    if (currentScore > 0) {
        // 当前分数计数动画
        animateCount(currentValue, 0, currentScore, 1000);
    }

    if (targetScore > 0) {
        // 目标分数计数动画
        animateCount(targetValue, 0, targetScore, 1000);
    }
}

/**
 * 数字计数动画
 */
function animateCount(element, start, end, duration) {
    let startTimestamp = null;
    const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        const value = Math.floor(progress * (end - start) + start);
        element.textContent = value;

        if (progress < 1) {
            window.requestAnimationFrame(step);
        }
    };
    window.requestAnimationFrame(step);
}

/**
 * 显示提示消息
 */
function showAlert(type, message) {
    // 移除现有的提示
    document.querySelectorAll('.alert').forEach(alert => alert.remove());

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3`;
    alertDiv.style.zIndex = '1060';
    alertDiv.innerHTML = `
        <i class="bi bi-${type === 'success' ? 'check-circle' : 
                         type === 'warning' ? 'exclamation-triangle' : 
                         type === 'info' ? 'info-circle' : 'exclamation-triangle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alertDiv);

    // 自动消失
    if (type === 'success' || type === 'info') {
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 5000);
    }
}

/**
 * 获取 CSRF token
 */
function getCSRFToken() {
    const csrfInput = document.querySelector('[name=csrfmiddlewaretoken]');
    return csrfInput ? csrfInput.value : '';
}

/**
 * 加载更多数据
 */
function loadMoreData() {
    console.log('加载更多数据功能开发中');
}

/**
 * 刷新数据
 */
function refreshData() {
    console.log('刷新数据功能开发中');
    // 这里可以添加数据刷新逻辑
    showAlert('info', '数据刷新功能开发中');
}

// 添加自定义样式
const style = document.createElement('style');
style.textContent = `
    /* 平滑滚动 */
    html {
        scroll-behavior: smooth;
    }
    
    /* 选择文本样式 */
    ::selection {
        background: rgba(67, 97, 238, 0.2);
        color: inherit;
    }
    
    /* 目标成绩卡片动画 */
    .target-score-card {
        cursor: pointer;
    }
    
    .target-score-card:hover .subject-icon {
        transform: scale(1.1) rotate(5deg);
        transition: transform 0.3s ease;
    }
    
    /* 分数对比区域动画 */
    .score-comparison {
        transition: all 0.3s ease;
    }
    
    /* 进度条动画 */
    .progress-bar-fill {
        position: relative;
        overflow: hidden;
    }
    
    .progress-bar-fill::after {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
        animation: shimmer 2s infinite;
    }
    
    @keyframes shimmer {
        0% { left: -100%; }
        100% { left: 100%; }
    }
    
    /* 范围条动画 */
    .range-safety, .range-realistic, .range-ideal {
        transition: width 0.8s ease;
    }
    
    .range-current {
        transition: left 1s ease;
    }
    
    /* 统计卡片悬停效果 */
    .stat-item:hover .stat-icon {
        transform: scale(1.1);
        transition: transform 0.3s ease;
    }
`;
document.head.appendChild(style);

// 页面加载完成后的初始化
console.log('学生详情页面初始化完成');

// 导出函数供其他脚本使用
window.StudentDetail = {
    initTooltips,
    initSubjectToggle,
    initNoteToggle,
    initTargetScoreCards,
    initAnalysisCardInteractions,
    initProgressAnimations,
    initRelativeTimeFallback,
    initDeleteConfirmations,
    initScoreActionTooltips,
    initScoreRangeCalculations,
    showAlert,
    loadMoreData,
    refreshData
};